import React, { useState } from 'react';
import { Button ,Icon, Input ,Card , Spin ,message } from 'antd';
import 'antd/dist/antd.css';
import '../static/css/Login.css';
import servicePath from '../config/api';
import axios from 'axios';


function Login(props) {
 const [ userName , setUserName ] = useState ('')
 const [ passWord , setPassWord ] = useState ('')
 const [ isLoading , setIsLoading ] = useState (false)


 const checkLogin = ()=>{
    setIsLoading(true)
    if(!userName){
       message.error('用户名不为空！')
       setTimeout(()=>{
        setIsLoading(false)  
       },500)
       return false
    }else if(!passWord){
        message.error('密码不为空！')
        setTimeout(()=>{
            setIsLoading(false)  
           },500)
        return false
    }
    let dataProps = { 
        'userName' : userName,
        'passWord' : passWord
     }

     axios({
         method : 'post',
         url : servicePath.checkLogin,
         data : dataProps,   // 传递的参数
         withCredentials : true  // 前后端共享 session
     }).then(
         res=>{
            setIsLoading(false)   //取消重复提交
            if(res.data.data === '登录成功'){
                localStorage.setItem('openId',res.data.openId)  // 把openId存到localStorage里
                props.history.push('/index')      //   登录成功跳转到首页
            }else{
                message.error('用户名密码错误 ！')
            }
         }
     )

}
    return (
        <div className = "login-div">
           <Spin tip="Loading..." spinning={isLoading}>
                <Card title="SHARk&nbsp;&nbsp;&nbsp;Blog" bordered={true} style={{ width : '400px'}}>
                     <Input 
                        id="userName"
                        size="large"
                        placeholder="请输入你的用户名"
                        prefix={<Icon type="user" style={{color:'rgba(0,0,0,0.25)'}}/>}
                        onChange={(e)=>{setUserName(e.target.value)}}
                     />
                    <br/><br/>
                    <Input.Password
                        id="passWord"
                        size="large"
                        placeholder="请输入你的密码"
                        prefix={<Icon type="key" style={{color:'rgba(0,0,0,0.25)'}}/>}
                        onChange={(e)=>{setPassWord(e.target.value)}}
                     />
                     <br/><br/>
                     <Button type="primary" size="large" block onClick={checkLogin} >登录</Button>
                </Card>
           </Spin>
        </div>
    );
    
}


export default Login